<?php

namespace App\Http\Controllers\Guard\Dev;

use App\Http\Controllers\Common\GuardController;
use App\Models\Dev\CoalArea;
use App\Models\Dev\DevInfo;
use App\Models\Dev\DevLog;
use Illuminate\Http\Request;

class DevLogController extends GuardController {


    public function __construct() {
        $this->instance = new DevLog();
    }

    public function lst(Request $request) {
        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',20);


        $conditions = $request->input();

        $records = $this->instance->getLst($conditions)->paginate($pageSize,$this->getCol,'page',$page);
        return responseSuccess($records->items(),$records->total());

    }

    public function add(Request $request) {
        $info = $request->input();
        $this->validate($request, [
            'people'=>'required',
            'dev_id'=>'required',
            'area'=>'required',
            'date'=>'required',
        ],[],[
            'people'=>'负责人'
        ]);

        //添加log记录
        $info['coal'] = isset($info['area'][0])?CoalArea::query()->find($info['area'][0])->name:'';
        $info['region'] = isset($info['area'][1])?CoalArea::query()->find($info['area'][1])->name:'';
        $info['local'] = isset($info['area'][2])?CoalArea::query()->find($info['area'][2])->name:'';
        $info['area'] = implode(',', $info['area']);
        $record = $this->instance->updateOrCreate(['id'=>$info['id']??0],$info);

        //修改设备的信息
        $dev = DevInfo::query()->find($info['dev_id']);
        $dev->coal = $info['coal'];
        $dev->region = $info['region'];
        $dev->local = $info['local'];
        $dev->area = $info['area'];
        $dev->busy = $info['oper_type']==1?'在用':'回收';
        $dev->save();


        return responseSuccess($record->toArray(),1);
    }

    public function detail(Request $request){
        $id = $request->input('id',0);
        $record = $this->instance->getRecordById($id);
        return responseSuccess($record->toArray(),1);
    }

    public function change(Request $request) {
        $id = $request->input('id',0);
        $status = $request->input('status');
        $this->instance->changeColById($id, compact('status'));
        return responseSuccess();
    }

    public function del(Request $request) {
        $id = $request->input('id',0);
        $this->instance->delRecordById($id);
        return responseSuccess();
    }
}
